<template>
  <div class="role-management">
    <h2>角色管理</h2>
    <el-container>
      <el-aside width="200px" class="menu-section">
        <el-select v-model="selectedRole" placeholder="请选择角色" @change="loadRolePermissions">
          <el-option v-for="role in roleList" :key="role.roleName" :label="role.roleName" :value="role.id">
          </el-option>
        </el-select>
        <div class="add-role">
          <el-button type="text" @click="addRole">+ 新增角色</el-button>
        </div>
      </el-aside>

      <el-container>
        <el-main>
          <h3>管理角色权限</h3>
          <el-row :gutter="20" class="permissions-section">
            <el-col :span="24">
              <el-checkbox v-model="allSelected" @change="toggleAll">全部</el-checkbox>
            </el-col>

            <el-col :span="6" v-for="item in permissions" :key="item.permissionName">
              <el-checkbox v-model="item.selected" @change="updateAllSelected">{{ item.permissionName === '签约管理'
                  ? '查看待处理签约、编辑待处理签约、删除待处理签约、导出待处理签约' : item.permissionName }}</el-checkbox>
              <div class="sub-permissions">
                <el-checkbox v-for="sub in item.subPermission" :key="sub.roleName" v-model="sub.checked"
                             @change="updateAllSelected">{{ sub.roleName === '系统管理员'? '全部权限' : sub.roleName }}
                </el-checkbox>
              </div>
            </el-col>
          </el-row>
          <div class="save-button">
            <el-button type="primary" @click="savePermissions">保存</el-button>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      roleList: [],
      permissions: [],
      selectId:null,
      selectedRole: null,
      subPermission: [],
      allSelected: false,
      current: 1,
      pageSize: 10,
      roleSelected: {},
      rolesForCheckbox: [],
      totalSelectedPermissions: 0,
      totalPermissions: 0
    };
  },
  computed: {
    computedPermissions() {
      const roleData = this.permissions.find(item => item.roleName === this.selectedRole);
      return roleData? roleData.permissions : [];
    }
  },
  methods: {
    async addRole() {
      const newRoleName = prompt("请输入新角色名称：");
      if (newRoleName) {
        try {
          await axios.post('http://localhost:8230/xt-roles/change', { roleName: newRoleName });
          this.fetchRoleList();
        } catch (error) {
          console.error('添加角色失败', error);
        }
      }
    },
    async savePermissions() {
      if (!this.selectedRole) {
        return this.$message.warning('请先选择一个角色');
      }

      console.log(this.permissions);

      /*const selectedPermissions = this.permissions.map(item => ({
        permissionId: item.selected? item.permissionId : [] // 确保每个权限对象都有 permissionid
      }));*/
      let selectedPermissions=[];
      for(let index in this.permissions){
        console.log(index)
        if(this.permissions[index].selected){
          selectedPermissions.push(this.permissions[index].permissionId);
        }
      }

      try {
        console.log(selectedPermissions)
        const response = await axios.post('http://localhost:8230/xt-role-permissions/save', {
          roleId: this.selectedRole,
          permissionIds: selectedPermissions
        });

        if (response.data.success) { // 假设后端返回的data中有success标志位
          this.$message.success('权限已保存');
        } else {
          this.$message.error('权限已保存');
        }
      } catch (error) {
        console.error('保存权限失败:', error.response ? error.response.data : error.message);
      }
    },

    async loadRolePermissions() {

      if (!this.selectedRole) {
        return this.$message.warning('请先选择一个角色');
      }

      try {
        const response = await axios.post(`http://localhost:8230/xt-role-permissions/cc/${this.current}/${this.pageSize}`, {
          roleId: this.selectedRole
        });
        if (response.data && response.data.data.records && Array.isArray(response.data.data.records)) {
          this.permissions = response.data.data.records.map(item => {
            // 检查 item.permi 是否存在
            const permissionName = item.permissionName || '未知权限'; // 如果没有permi则使用‘未知权限’作为默认值
            console.log(this.permissionName)
            return {
              permissionId: item.permissionId,
              permissionName,
              selected: false,
              subPermission: item.subPermission ? item.subPermission.map(sub => ({ roleName: sub, checked: false })) : []
            };
          });

          console.log("Permissions for role loaded:", this.permissions);
        } else {
          this.$message.error('返回的权限数据格式不正确');
          console.warn('权限数据格式不符合预期:', response.data);
        }
      } catch (error) {
        console.error('加载角色权限失败:', error.response ? error.response.data : error.message);
        this.$message.error('加载角色权限失败');
      }
    },

    toggleAll() {
      this.allSelected = !this.allSelected;
      this.permissions.forEach(item => {
        item.selected = this.allSelected;
        item.subPermission.forEach(sub => {
          sub.checked = this.allSelected;
        });
      });
      Object.keys(this.roleSelected).forEach(role => {
        this.roleSelected[role] = this.allSelected;
      });
    },
    async fetchRoleList() {
      try {
        const response = await axios.post(`http://localhost:8230/xt-roles/all/${this.current}/${this.pageSize}`, {
        });
        this.roleList = response.data.data.records;
        this.rolesForCheckbox = response.data.data.records.map(item => item.roleName);
        console.log("Roles loaded:", this.roleList);
      } catch (error) {
        console.error('获取角色列表失败:', error);
      }
    },
    async loadAllPermissions() {
      const requestBody = {
        current: this.current,
        pageSize: this.pageSize
      };

      try {
        const response = await axios.post(`http://localhost:8230/xt-permissions/bll/${this.current}/${this.pageSize}`, requestBody);

        // 检查返回的结构
        if (response.data && response.data.data && Array.isArray(response.data.data.records)) {
          this.permissions = response.data.data.records.map(item => ({
            roleName: item.roleName, // 根据真实数据结构修改
            permissions: Array.isArray(item.permissions) ? item.permissions.map(perm => ({
              permissionName: perm.permissionName,
              selected: false,
              subPermission: Array.isArray(perm.subPermission) ? perm.subPermission.map(sub => ({
                roleName: sub, // 假设sub是字符串
                checked: false
              })) : [] // 确保subPermission为数组
            })) : [] // 确保permissions为数组
          }));

          // 计算总权限数
          this.totalPermissions = this.permissions.reduce((total, item) => total + 1 + (item.permissions.length || 0), 0);
          console.log("All permissions loaded:", this.permissions);
        } else {
          console.warn('响应数据格式不符合预期:', response.data);
        }
      } catch (error) {
        console.error('获取所有权限失败:', error.response ? error.response.data : error.message);
      }
    },
    updateAllSelected() {
      let selectedCount = 0;
      this.permissions.forEach(item => {
        if (item.selected) selectedCount++;
        item.subPermission.forEach(sub => {
          if (sub.checked) selectedCount++;
        });
      });
      this.allSelected = selectedCount === this.totalPermissions;
    }
  },
  created() {
    this.fetchRoleList();
    this.loadAllPermissions();
  }
};
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.menu-section {
  background: #f5f5f5;
  height: 100%;
  padding: 10px;
  border-right: 1px solid #d3dce6;
}

.add-role {
  margin-top: 10px;
}

.permissions-section {
  padding: 20px;
  background: #fff;
  margin: 0;
}

.sub-permissions {
  margin-top: 10px;
  margin-left: 20px;
}

.save-button {
  text-align: right;
  margin-top: 20px;
}

.el-checkbox__input.is-checked +.el-checkbox__label {
  color: #409eff;
}
</style>